package org.dbstar.scheduler.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.struts2.interceptor.PrincipalAware;
import org.apache.struts2.interceptor.PrincipalProxy;
import org.dbstar.scheduler.beans.OperateType;
import org.dbstar.scheduler.control.OperateController;
import org.dbstar.scheduler.control.exception.DaoException;
import org.dbstar.scheduler.identifier.Identifier;
import org.dbstar.scheduler.ldap.SchedulerUserDetailsContextMapper;


/**
 * @author bdai
 * @date 2011-6-10
 * 
 */
public abstract class ActionSupport implements ActionBase, PrincipalAware {
	private PrincipalProxy principalProxy;
	protected String user = "Anonymous";
	private OperateController operateController;

	private List<String> messages = new ArrayList<String>();

	@Override
	public final void setPrincipalProxy(PrincipalProxy principalProxy) {
		this.principalProxy = principalProxy;
		if (principalProxy.getUserPrincipal() != null) {
			this.user = principalProxy.getUserPrincipal().getName();
		}
	}

	protected final PrincipalProxy getPrincipalProxy() {
		return principalProxy;
	}

	protected final boolean isSuperVisor() {
		if (principalProxy == null) {
			return false;
		} else {
			return principalProxy.isUserInRole(SchedulerUserDetailsContextMapper.SUPERVISOR.getAuthority());
		}
	}

	public final void setOperateController(OperateController operateController) {
		this.operateController = operateController;
	}

	protected final void operate(OperateType operate, String parameter) throws DaoException {
		operateController.operate(user, operate, parameter);
	}

	protected final void operate(OperateType operate, Identifier identifier) throws DaoException {
		operate(operate, identifier.getStringIdentifier());
	}

	public final void setActionMessages(Collection<String> messages) {
		this.messages.clear();
		this.messages.addAll(messages);
	}

	public final Collection<String> getActionMessages() {
		return messages;
	}

	protected final void addActionMessage(String aMessage) {
		messages.add(aMessage);
	}
}
